package com.weiyi.mashangzhu.Roomer.Activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import android.widget.HorizontalScrollView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.TextureMapView;
import com.baidu.mapapi.map.UiSettings;
import com.baidu.mapapi.model.LatLng;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.squareup.okhttp.Request;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXImageObject;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.weiyi.mashangzhu.API.API;
import com.weiyi.mashangzhu.Application.MyApp;
import com.weiyi.mashangzhu.Base.BaseActivity;
import com.weiyi.mashangzhu.R;
import com.weiyi.mashangzhu.Roomer.Adapter.FacilityAdapter;
import com.weiyi.mashangzhu.Roomer.Adapter.Facility_PopAdapter;
import com.weiyi.mashangzhu.Roomer.Adapter.IntroAdapter;
import com.weiyi.mashangzhu.Roomer.Bean.FacilityInfo;
import com.weiyi.mashangzhu.Roomer.Bean.HouseDetailsBean;
import com.weiyi.mashangzhu.Roomer.Bean.IntroInfo;
import com.weiyi.mashangzhu.Utils.GlideImgManager;
import com.weiyi.mashangzhu.Utils.LoadingDialog;
import com.weiyi.mashangzhu.Utils.ProgressDialog;
import com.weiyi.mashangzhu.Utils.SPUtils;
import com.weiyi.mashangzhu.Utils.T;
import com.weiyi.mashangzhu.Utils.UiUtil;
import com.weiyi.mashangzhu.Weight.MyListView;
import com.weiyi.mashangzhu.Weight.calendartest.entity.DayTimeEntity;
import com.weiyi.mashangzhu.Weight.calendartest.entity.MonthTimeEntity;
import com.weiyi.mashangzhu.Weight.calendartest.entity.UpdataCalendar;
import com.weiyi.mashangzhu.Weight.calendartest.utils.MonthTimeAdapter_HouseDetails;
import com.weiyi.mashangzhu.Weight.calendartest.utils.SharePreferences;
import com.weiyi.mashangzhu.Weight.scrollview.MonitorScrollView;
import com.weiyi.mashangzhu.Weight.scrollview.listener.OnScrollListener;
import com.weiyi.mashangzhu.easemob.Constant;
import com.weiyi.mashangzhu.easemob.db.ChatDao;
import com.weiyi.mashangzhu.easemob.ui.ChatActivity;
import com.weiyi.mashangzhu.wxapi.simcpux.BmpToByteArray;
import com.zhy.android.percent.support.PercentLinearLayout;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;

import static com.igexin.sdk.GTServiceManager.context;

public class HouseDetailsActivity extends BaseActivity {

    @BindView(R.id.vp)
    ViewPager vp;
    @BindView(R.id.onepage)
    ImageView onepage;
    @BindView(R.id.price)
    TextView price;
    @BindView(R.id.house_detail_title)
    TextView houseDetailTitle;
    @BindView(R.id.house_detail_owner_head)
    ImageView houseDetailOwnerHead;
    @BindView(R.id.house_detail_owner_nick)
    TextView houseDetailOwnerNick;
    @BindView(R.id.house_detail_owner_intro)
    TextView houseDetailOwnerIntro;
    @BindView(R.id.house_detail_intro)
    ListView houseDetailIntro;
    @BindView(R.id.house_detail_good_rate)
    TextView houseDetailGoodRate;
    @BindView(R.id.house_detail_good_number)
    TextView houseDetailGoodNumber;
    @BindView(R.id.house_detail_user_nick)
    TextView houseDetailUserNick;
    @BindView(R.id.house_detail_user_head)
    ImageView houseDetailUserHead;
    @BindView(R.id.house_detail_user_appraise)
    TextView houseDetailUserAppraise;
    @BindView(R.id.house_detail_user_time)
    TextView houseDetailUserTime;
    @BindView(R.id.house_detail_description)
    TextView houseDetailDescription;
    @BindView(R.id.house_detail_description_full)
    RelativeLayout houseDetailDescriptionFull;
    @BindView(R.id.house_detail_notice_in)
    TextView houseDetailNoticeIn;
    @BindView(R.id.house_detail_notice_out)
    TextView houseDetailNoticeOut;
    @BindView(R.id.house_detail_notice_card)
    TextView houseDetailNoticeCard;
    @BindView(R.id.house_detail_notice_pledge)
    TextView houseDetailNoticePledge;
    @BindView(R.id.title)
    PercentLinearLayout title;
    @BindView(R.id.scrollview)
    MonitorScrollView scrollview;
    @BindView(R.id.nums)
    TextView nums;
    @BindView(R.id.tv_top)
    TextView tvTop;
    @BindView(R.id.house_detail_description_icon)
    ImageView houseDetailDescriptionIcon;
    @BindView(R.id.house_detail_facility)
    GridView houseDetailFacility;
    @BindView(R.id.collect)
    ImageView collect;
    List<ImageView> imageViewList = new ArrayList<>();
    ImageView close;
    List<FacilityInfo> list = new ArrayList<>();
    List<FacilityInfo> list_yes = new ArrayList<>();
    List<FacilityInfo> list_no = new ArrayList<>();
    boolean flag = false;
    TextView pop_friend_wx, pop_friend_wxc, pop_off;
    private static final int STATE_SHRINK = 1;
    private static final int STATE_SPREAD = 2;
    private static int state = STATE_SHRINK;
    private static final int MAX_LINES = 5;
    TextureMapView mMapView = null;
    @BindView(R.id.more_house)
    PercentLinearLayout moreHouse;
    @BindView(R.id.scrollView)
    HorizontalScrollView scrollView;
    HouseDetailsBean houseDetailsBean;
    @BindView(R.id.time)
    TextView time;
    @BindView(R.id.parent)
    RelativeLayout ll;
    private TextView startTime;          //开始时间
    private TextView stopTime;           //结束时间
    String id, city;
    List<String> ids = new ArrayList<>();
    boolean[] flags;
    private RecyclerView reycycler;
    private MonthTimeAdapter_HouseDetails adapter;
    private ArrayList<MonthTimeEntity> datas;
    private List<String> urllist = new ArrayList<>();
    private List<String> urllist2 = new ArrayList<>();
    private List<String> urllist3 = new ArrayList<>();
    private String[] rulesList = null;
    private BaiduMap bdmap;
    public static DayTimeEntity startDay;
    public static DayTimeEntity stopDay;
    Bitmap bitmap = null;
    SharePreferences isPreferences;
    String start_time, stop_time, yajin, house_id;
    private IWXAPI msgApi;
    HouseDetailsBean.DataBean.HouseBean houseBean = null;
    ImageView img_share;
    MonitorScrollView scrollView1;


    Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            if (msg.what == 0) {
                vp.setCurrentItem(vp.getCurrentItem() + 1);
                handler.sendEmptyMessageDelayed(0, 2000);
            }
            return false;
        }
    });

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_house_details);
        ButterKnife.bind(this);

        id = getIntent().getStringExtra("id");
        city = getIntent().getStringExtra("city");
        Log.e("reeeeeeeee", "id=" + id);
//        T.showShort(this, "id=" + id);
        isPreferences = new SharePreferences(this);
        title.getBackground().setAlpha(0);
        tvTop.setVisibility(View.GONE);
        EventBus.getDefault().register(this);
        //配套设施
        list.add(new FacilityInfo(R.mipmap.wifi1, R.mipmap.wifi, "无线宽带"));
        list.add(new FacilityInfo(R.mipmap.tv1, R.mipmap.tv, "电视"));
        list.add(new FacilityInfo(R.mipmap.hot241, R.mipmap.hot24, "全天热水"));
        list.add(new FacilityInfo(R.mipmap.shower1, R.mipmap.shower, "淋浴"));
        list.add(new FacilityInfo(R.mipmap.washe1r, R.mipmap.washer, "洗衣机"));
        list.add(new FacilityInfo(R.mipmap.lift1, R.mipmap.lift, "电梯"));
        list.add(new FacilityInfo(R.mipmap.menjin1, R.mipmap.menjin, "门禁"));
        list.add(new FacilityInfo(R.mipmap.air1, R.mipmap.air, "空调"));
        list.add(new FacilityInfo(R.mipmap.heating1, R.mipmap.heating, "暖气"));
        list.add(new FacilityInfo(R.mipmap.slipper1, R.mipmap.slipper, "拖鞋"));
        list.add(new FacilityInfo(R.mipmap.cooking1, R.mipmap.cooking, "厨房"));
        list.add(new FacilityInfo(R.mipmap.wash1, R.mipmap.wash, "洗漱用品"));
        list.add(new FacilityInfo(R.mipmap.smoking1, R.mipmap.smoking, "允许吸烟"));
        initView();
        scrollChangeBarBg();
    }

    @Override
    protected void onResume() {
        super.onResume();
        moreHouse.removeAllViews();
        initView_resume();
        mMapView.onResume();
    }

    //初始化地图
    private void initMap(String lat, String lon) {
        bdmap = mMapView.getMap();
        setUserMapCenter(lat, lon);
        setMarker(lat, lon);
        UiSettings settings = bdmap.getUiSettings();
        settings.setAllGesturesEnabled(false);   //关闭一切手势操作
    }

    /**
     * 添加marker
     */
    private void setMarker(String lat, String lon) {
        Log.v("pcw", "setMarker : lat : " + lat + " lon : " + lon);
        //定义Maker坐标点
        LatLng point = new LatLng(Double.parseDouble(lat), Double.parseDouble(lon));
        //构建Marker图标
        BitmapDescriptor bitmap = BitmapDescriptorFactory.fromResource(R.mipmap.ad);
        //构建MarkerOption，用于在地图上添加Marker
        OverlayOptions option = new MarkerOptions().position(point).icon(bitmap);
        //在地图上添加Marker，并显示
        bdmap.addOverlay(option);
    }

    /**
     * 设置中心点
     */
    private void setUserMapCenter(String lat, String lon) {
        Log.v("pcw", "setUserMapCenter : lat : " + lat + " lon : " + lon);
        LatLng cenpt = new LatLng(Double.parseDouble(lat), Double.parseDouble(lon));
        //定义地图状态
        MapStatus mMapStatus = new MapStatus.Builder()
                .target(cenpt)
                .zoom(14)
                .build();
        //定义MapStatusUpdate对象，以便描述地图状态将要发生的变化
        MapStatusUpdate mMapStatusUpdate = MapStatusUpdateFactory.newMapStatus(mMapStatus);
        //改变地图状态
        bdmap.setMapStatus(mMapStatusUpdate);

    }

    //房屋描述文字的收起放开
    private void initHouseDescription() {

        if (state == STATE_SPREAD) {
            houseDetailDescription.setMaxLines(MAX_LINES);
            houseDetailDescription.requestLayout();
            houseDetailDescriptionIcon.setBackgroundResource(R.mipmap.pack);
            state = STATE_SHRINK;
        } else if (state == STATE_SHRINK) {
            houseDetailDescription.setMaxLines(Integer.MAX_VALUE);
            houseDetailDescription.requestLayout();
            houseDetailDescriptionIcon.setBackgroundResource(R.mipmap.pack2);
            state = STATE_SPREAD;
        }
    }


    public void initView_resume() {
        LoadingDialog.show(this);
        //获取房屋详情
        OkHttpUtils.get().addParams("token", SPUtils.get(this, "token", "") + "")
                .addParams("id", id)
                .addParams("hCity", city)
                .url(API.BaseApi_R + API.HouseDetails_Api).build().execute(new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {
                LoadingDialog.dismiss(HouseDetailsActivity.this);
                T.showShort(HouseDetailsActivity.this, "网络连接失败，请检查一下网络设置");
            }

            @Override
            public void onResponse(String response) {
                LoadingDialog.dismiss(HouseDetailsActivity.this);
                Gson gson = new Gson();
                houseDetailsBean = gson.fromJson(response, HouseDetailsBean.class);
                houseBean = houseDetailsBean.getData().getHouse();
                List<HouseDetailsBean.DataBean.GroomhouselistBean> groomhouselist = new ArrayList<HouseDetailsBean.DataBean.GroomhouselistBean>();
                groomhouselist = houseDetailsBean.getData().getGroomhouselist();
                ids.clear();
                for (int i = 0; i < groomhouselist.size(); i++) {
                    ids.add(groomhouselist.get(i).getId() + "");
                }
                if (groomhouselist!=null&&groomhouselist.size()!=0){
                    //推荐房源
                    LayoutInflater inflater = LayoutInflater.from(HouseDetailsActivity.this);
                    for (int i = 0; i < groomhouselist.size(); i++) {
                        urllist3.clear();
//                    flags[i] = false;
                        View view = inflater.inflate(R.layout.item_housing_list, null);
                        TextView num = (TextView) view.findViewById(R.id.price_num);
                        final ImageButton collect_gr = (ImageButton) view.findViewById(R.id.housing_mark);
                        ImageView img = (ImageView) view.findViewById(R.id.housing_img);
                        TextView title = (TextView) view.findViewById(R.id.housing_title);
                        TextView grade = (TextView) view.findViewById(R.id.housing_grade);
                        TextView type = (TextView) view.findViewById(R.id.housing_type);
                        num.setText("¥" + groomhouselist.get(i).getHPrice() + "");
                        if (groomhouselist.get(i).getIsCollect().equals("0")) {
                            collect_gr.setImageResource(R.mipmap.collect);
                        } else {
                            collect_gr.setImageResource(R.mipmap.collect1);
                        }
                        //!houseDetailsBean.getData().getGroomhouselist().get(i).getHImg1().equals("") ||
                        if (houseDetailsBean.getData().getGroomhouselist().get(i).getHImg1() != null) {
                            urllist3.add(houseDetailsBean.getData().getGroomhouselist().get(i).getHImg1());
                        }
                        if (houseDetailsBean.getData().getGroomhouselist().get(i).getHImg2() != null) {
                            urllist3.add(houseDetailsBean.getData().getGroomhouselist().get(i).getHImg2());
                        }
                        if (houseDetailsBean.getData().getGroomhouselist().get(i).getHImg3() != null) {
                            urllist3.add(houseDetailsBean.getData().getGroomhouselist().get(i).getHImg3());
                        }
                        if (houseDetailsBean.getData().getGroomhouselist().get(i).getHImg4() != null) {
                            urllist3.add(houseDetailsBean.getData().getGroomhouselist().get(i).getHImg4());
                        }
                        if (houseDetailsBean.getData().getGroomhouselist().get(i).getHImg5() != null) {
                            urllist3.add(houseDetailsBean.getData().getGroomhouselist().get(i).getHImg5());
                        }
                        if (houseDetailsBean.getData().getGroomhouselist().get(i).getHImg6() != null) {
                            urllist3.add(houseDetailsBean.getData().getGroomhouselist().get(i).getHImg6());
                        }
                        GlideImgManager.glideLoader(HouseDetailsActivity.this, API.BaseApi_url + urllist3.get(0), R.mipmap.errer, img);
                        title.setText(groomhouselist.get(i).getHTitle() + "");
                        grade.setText(groomhouselist.get(i).getScoreavegroom() + "");
                        for (int j = 0; j < groomhouselist.size(); j++) {
                            Log.e("rrrrrrr", "===" + groomhouselist.get(j).getIsCollect());
                        }
                        moreHouse.addView(view);
                        type.setText(groomhouselist.get(i).getHRoom() + "居  |  " + groomhouselist.get(i).getHDistrict());
                        final int finalI = i;
                        final List<HouseDetailsBean.DataBean.GroomhouselistBean> finalGroomhouselist2 = groomhouselist;
                        final int finalI2 = i;
                        collect_gr.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                if (SPUtils.get(HouseDetailsActivity.this, "isLogin", "0").equals("0")) {
                                    UiUtil.startActivity(HouseDetailsActivity.this, LoginActivity.class);
                                } else if (SPUtils.get(HouseDetailsActivity.this, "isLogin", "0").equals("1")) {
                                    //已登录 进行收藏操作
                                    OkHttpUtils.get()
                                            .addParams("token", SPUtils.get(HouseDetailsActivity.this, "token", "") + "")
                                            .addParams("id", finalGroomhouselist2.get(finalI2).getId() + "")
                                            .url(API.BaseApi_R + API.CollectHouse_Api)
                                            .build()
                                            .execute(new StringCallback() {
                                                @Override
                                                public void onError(Request request, Exception e) {
                                                    T.showShort(context, "网络连接失败");

                                                }

                                                @Override
                                                public void onResponse(String response) {
                                                    try {
                                                        JSONObject jsonObject = new JSONObject(response);
                                                        if (jsonObject.getInt("status") == 0) {
                                                            if (jsonObject.getString("msg").equals("收藏成功")) {
                                                                collect_gr.setImageResource(R.mipmap.collect1);
                                                                finalGroomhouselist2.get(finalI2).setIsCollect("1");
                                                                T.showShort(HouseDetailsActivity.this, "收藏成功");
                                                            } else {
                                                                collect_gr.setImageResource(R.mipmap.collect);
                                                                finalGroomhouselist2.get(finalI2).setIsCollect("0");
                                                                T.showShort(HouseDetailsActivity.this, "取消收藏成功");
                                                            }
                                                        } else {
                                                            T.showShort(context, jsonObject.getString("msg"));
                                                        }
                                                    } catch (JSONException e) {
                                                        e.printStackTrace();
                                                    }
                                                    Log.e("rrrrrrrrrrr", "==" + response);
                                                }
                                            });


//                                if (flags[finalI] == false) {
//                                    flags[finalI] = true;
//                                    collect.setImageResource(R.mipmap.collect1);
//                                } else {
//                                    flags[finalI] = false;
//                                    collect.setImageResource(R.mipmap.collect);
//                                }
                                }
                            }
                        });
                        final List finalGroomhouselist = groomhouselist;
                        final List<HouseDetailsBean.DataBean.GroomhouselistBean> finalGroomhouselist1 = groomhouselist;
                        final int finalI1 = i;
                        view.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                Intent itent = new Intent(HouseDetailsActivity.this, HouseDetailsActivity.class);
                                itent.putExtra("id", ids.get(finalI) + "");
                                itent.putExtra("city", finalGroomhouselist1.get(finalI1).getHCity() + "");
                                HouseDetailsActivity.this.startActivity(itent);

                            }
                        });

                    }


                }

            }
        });


        super.initView();
    }


    //初始化界面的内容
    @Override
    public void initView() {

        mMapView = (TextureMapView) findViewById(R.id.bmapView);

        LoadingDialog.show(this);
        //获取房屋详情
        OkHttpUtils.get().addParams("token", SPUtils.get(this, "token", "") + "")
                .addParams("id", id)
                .addParams("hCity", city)
                .url(API.BaseApi_R + API.HouseDetails_Api).build().execute(new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {
                LoadingDialog.dismiss(HouseDetailsActivity.this);
                T.showShort(HouseDetailsActivity.this, "网络连接失败，请检查一下网络设置");
            }

            @Override
            public void onResponse(String response) {
                LoadingDialog.dismiss(HouseDetailsActivity.this);
                Gson gson = new Gson();
                houseDetailsBean = gson.fromJson(response, HouseDetailsBean.class);
                houseBean = houseDetailsBean.getData().getHouse();
                getShare(houseBean);
                List<HouseDetailsBean.DataBean.EvalistBean> evalistBeanList = new ArrayList<HouseDetailsBean.DataBean.EvalistBean>();
                evalistBeanList = houseDetailsBean.getData().getEvalist();
                List<HouseDetailsBean.DataBean.MatchlistBean> matchlistBeanList = new ArrayList<HouseDetailsBean.DataBean.MatchlistBean>();
                matchlistBeanList = houseDetailsBean.getData().getMatchlist();
                HouseDetailsBean.DataBean.ReturnpolicyBean returnpolicybean = houseDetailsBean.getData().getReturnpolicy();
                rulesList = returnpolicybean.getAllCounts().trim().split("。");
//                List<HouseDetailsBean.DataBean.GroomhouselistBean> groomhouselist = new ArrayList<HouseDetailsBean.DataBean.GroomhouselistBean>();
//                groomhouselist = houseDetailsBean.getData().getGroomhouselist();
                //初始化地图定位
                initMap(houseBean.getHLat(), houseBean.getHLog());

//                flags = new boolean[groomhouselist.size()];
//                for (int i = 0; i < groomhouselist.size(); i++) {
//                    ids.add(groomhouselist.get(i).getId() + "");
//                }
                Log.e("bbbbbbb", "collect=" + houseDetailsBean.getData().getHouse().getIsCollect());
                if (houseDetailsBean.getData().getHouse().getIsCollect().equals("0")) {
                    collect.setImageResource(R.mipmap.collect);
                } else if (houseDetailsBean.getData().getHouse().getIsCollect().equals("1")) {
                    collect.setImageResource(R.mipmap.collect1);
                }
                urllist.clear();
                //设置轮播图  !houseDetailsBean.getData().getHouse().getHImg1().equals("") ||
                if (houseDetailsBean.getData().getHouse().getHImg1() != null) {
                    urllist.add(houseDetailsBean.getData().getHouse().getHImg1());
                }
                if (houseDetailsBean.getData().getHouse().getHImg2() != null) {
                    urllist.add(houseDetailsBean.getData().getHouse().getHImg2());
                }
                if (houseDetailsBean.getData().getHouse().getHImg3() != null) {
                    urllist.add(houseDetailsBean.getData().getHouse().getHImg3());
                }
                if (houseDetailsBean.getData().getHouse().getHImg4() != null) {
                    urllist.add(houseDetailsBean.getData().getHouse().getHImg4());
                }
                if (houseDetailsBean.getData().getHouse().getHImg5() != null) {
                    urllist.add(houseDetailsBean.getData().getHouse().getHImg5());
                }
                if (houseDetailsBean.getData().getHouse().getHImg6() != null) {
                    urllist.add(houseDetailsBean.getData().getHouse().getHImg6());
                }
                if (urllist.size() > 1 && urllist.size() <= 3) {
                    onepage.setVisibility(View.GONE);
                    urllist2.addAll(urllist);
                    urllist2.addAll(urllist);
                    setViewPager();
                } else if (urllist.size() == 1) {
                    Glide.with(HouseDetailsActivity.this).load(API.BaseApi_url + urllist.get(0)).error(R.mipmap.ic_launcher).into(onepage);
                    onepage.setVisibility(View.VISIBLE);
                } else {
                    onepage.setVisibility(View.GONE);
                    urllist2.addAll(urllist);
                    setViewPager();
                }

                //设置价格
                price.setText("¥" + houseBean.getHPrice() + "/每晚");
                //设置标题
                houseDetailTitle.setText(houseBean.getHTitle() + "");
                //设置房东信息
                GlideImgManager.glideLoader(HouseDetailsActivity.this, API.BaseApi_url + houseDetailsBean.getData().getUHead(), R.mipmap.errer, houseDetailOwnerHead, 0);
                houseDetailOwnerNick.setText(houseDetailsBean.getData().getUNickname() + "");
                houseDetailOwnerIntro.setText(houseBean.getHostrat() != null ? "实名认证 | 好评率" + houseBean.getHostrat() : "实名认证 | 好评率0");

                /**加载房屋简介列表*/
                initHouseIntro(houseBean, houseDetailIntro);

                //设置房屋好评率
                houseDetailGoodRate.setText(houseBean.getPositiverat() != null ? "好评率  " + houseBean.getPositiverat() : "好评率  0");
                //设置评论条数
                houseDetailGoodNumber.setText(evalistBeanList.size() + "评价");
                //评论人的头像
                if (evalistBeanList.size() == 0) {
                    houseDetailUserHead.setVisibility(View.GONE);
                } else {
                    houseDetailUserHead.setVisibility(View.VISIBLE);
                    GlideImgManager.glideLoader(HouseDetailsActivity.this, API.BaseApi_url + evalistBeanList.get(0).getCustomerHead(), R.mipmap.errer, houseDetailUserHead, 0);

                }
                if (evalistBeanList != null && evalistBeanList.size() != 0) {
                    //评论人用户名
                    houseDetailUserNick.setText(evalistBeanList.get(0).getCustomerName() + "");
                    //评论内容
                    houseDetailUserAppraise.setText(evalistBeanList.get(0).getEContent() + "");
                    //评论时间
                    houseDetailUserTime.setText(evalistBeanList.get(0).getETime() + "");
                }

                //房屋描述
                houseDetailDescription.setText(houseBean.getHIntro() + "");
                if (houseDetailDescription.getLineCount() == 5) {
                    houseDetailDescriptionFull.setVisibility(View.VISIBLE);
                } else {
                    houseDetailDescriptionFull.setVisibility(View.INVISIBLE);
                }
                //配套设施
                List<String> matchNameList = new ArrayList<String>();
                if (matchlistBeanList.size() != 0) {
                    for (int i = 0; i < matchlistBeanList.size(); i++) {
                        matchNameList.add(matchlistBeanList.get(i).getMName());
                    }
                }

                for (int i = 0; i < list.size(); i++) {
                    if (matchNameList.contains(list.get(i).getTitle())) {
                        list_yes.add(list.get(i));
                    } else {
                        list_no.add(list.get(i));
                    }
                }
                Log.e("reeeeeeee", "size=" + list_yes.size());
                initHouseFacility();

                //设置入住时间
                houseDetailNoticeIn.setText(returnpolicybean.getRetuliveTime() + "");
                //设置退房时间
                houseDetailNoticeOut.setText(returnpolicybean.getRetuleaveTime() + "");
                //是否需要身份证
                if (returnpolicybean.getIdCardneed() == 1) {
                    houseDetailNoticeCard.setText("需要");
                } else {
                    houseDetailNoticeCard.setText("不需要");
                }
                //押金
                houseDetailNoticePledge.setText("¥" + houseBean.getHdeposit());
                yajin = houseBean.getHdeposit() + "";
                house_id = houseBean.getId() + "";

//                //推荐房源
//                LayoutInflater inflater = LayoutInflater.from(HouseDetailsActivity.this);
//                for (int i = 0; i < groomhouselist.size(); i++) {
//                    urllist3.clear();
//                    flags[i] = false;
//                    View view = inflater.inflate(R.layout.item_housing_list, null);
//                    TextView num = (TextView) view.findViewById(R.id.price_num);
//                    final ImageButton collect_gr = (ImageButton) view.findViewById(R.id.housing_mark);
//                    ImageView img = (ImageView) view.findViewById(R.id.housing_img);
//                    TextView title = (TextView) view.findViewById(R.id.housing_title);
//                    TextView grade = (TextView) view.findViewById(R.id.housing_grade);
//                    TextView type = (TextView) view.findViewById(R.id.housing_type);
//                    num.setText("¥" + groomhouselist.get(i).getHPrice() + "");
//                    if (groomhouselist.get(i).getIsCollect().equals("0")) {
//                        collect_gr.setImageResource(R.mipmap.collect);
//                    } else {
//                        collect_gr.setImageResource(R.mipmap.collect1);
//                    }
//                    //!houseDetailsBean.getData().getGroomhouselist().get(i).getHImg1().equals("") ||
//                    if (houseDetailsBean.getData().getGroomhouselist().get(i).getHImg1() != null) {
//                        urllist3.add(houseDetailsBean.getData().getGroomhouselist().get(i).getHImg1());
//                    }
//                    if (houseDetailsBean.getData().getGroomhouselist().get(i).getHImg2() != null) {
//                        urllist3.add(houseDetailsBean.getData().getGroomhouselist().get(i).getHImg2());
//                    }
//                    if (houseDetailsBean.getData().getGroomhouselist().get(i).getHImg3() != null) {
//                        urllist3.add(houseDetailsBean.getData().getGroomhouselist().get(i).getHImg3());
//                    }
//                    if (houseDetailsBean.getData().getGroomhouselist().get(i).getHImg4() != null) {
//                        urllist3.add(houseDetailsBean.getData().getGroomhouselist().get(i).getHImg4());
//                    }
//                    if (houseDetailsBean.getData().getGroomhouselist().get(i).getHImg5() != null) {
//                        urllist3.add(houseDetailsBean.getData().getGroomhouselist().get(i).getHImg5());
//                    }
//                    if (houseDetailsBean.getData().getGroomhouselist().get(i).getHImg6() != null) {
//                        urllist3.add(houseDetailsBean.getData().getGroomhouselist().get(i).getHImg6());
//                    }
//                    GlideImgManager.glideLoader(HouseDetailsActivity.this, API.BaseApi_url + urllist3.get(0), R.mipmap.errer, img);
//                    title.setText(groomhouselist.get(i).getHTitle() + "");
//                    grade.setText(groomhouselist.get(i).getScoreavegroom() + "");
//                    for (int j = 0; j < groomhouselist.size(); j++) {
//                        Log.e("rrrrrrr", "===" + groomhouselist.get(j).getIsCollect());
//                    }
//                    moreHouse.addView(view);
//                    type.setText(groomhouselist.get(i).getHRoom() + "居  |  " + groomhouselist.get(i).getHDistrict());
//                    final int finalI = i;
//                    final List<HouseDetailsBean.DataBean.GroomhouselistBean> finalGroomhouselist2 = groomhouselist;
//                    final int finalI2 = i;
//                    collect_gr.setOnClickListener(new View.OnClickListener() {
//                        @Override
//                        public void onClick(View v) {
//                            if (SPUtils.get(HouseDetailsActivity.this, "isLogin", "0").equals("0")) {
//                                UiUtil.startActivity(HouseDetailsActivity.this, LoginActivity.class);
//                            } else if (SPUtils.get(HouseDetailsActivity.this, "isLogin", "0").equals("1")) {
//                                //已登录 进行收藏操作
//                                OkHttpUtils.get()
//                                        .addParams("token", SPUtils.get(HouseDetailsActivity.this, "token", "") + "")
//                                        .addParams("id", finalGroomhouselist2.get(finalI2).getId() + "")
//                                        .url(API.BaseApi_R + API.CollectHouse_Api)
//                                        .build()
//                                        .execute(new StringCallback() {
//                                            @Override
//                                            public void onError(Request request, Exception e) {
//                                                T.showShort(context, "网络连接失败");
//
//                                            }
//
//                                            @Override
//                                            public void onResponse(String response) {
//                                                try {
//                                                    JSONObject jsonObject = new JSONObject(response);
//                                                    if (jsonObject.getInt("status") == 0) {
//                                                        if (jsonObject.getString("msg").equals("收藏成功")) {
//                                                            collect_gr.setImageResource(R.mipmap.collect1);
//                                                            finalGroomhouselist2.get(finalI2).setIsCollect("1");
//                                                            T.showShort(HouseDetailsActivity.this, "收藏成功");
//                                                        } else {
//                                                            collect_gr.setImageResource(R.mipmap.collect);
//                                                            finalGroomhouselist2.get(finalI2).setIsCollect("0");
//                                                            T.showShort(HouseDetailsActivity.this, "取消收藏成功");
//                                                        }
//                                                    } else {
//                                                        T.showShort(context, jsonObject.getString("msg"));
//                                                    }
//                                                } catch (JSONException e) {
//                                                    e.printStackTrace();
//                                                }
//                                                Log.e("rrrrrrrrrrr", "==" + response);
//                                            }
//                                        });


//                                if (flags[finalI] == false) {
//                                    flags[finalI] = true;
//                                    collect.setImageResource(R.mipmap.collect1);
//                                } else {
//                                    flags[finalI] = false;
//                                    collect.setImageResource(R.mipmap.collect);
//                                }
//                            }
//                        }
//                    });
//                    final List finalGroomhouselist = groomhouselist;
//                    final List<HouseDetailsBean.DataBean.GroomhouselistBean> finalGroomhouselist1 = groomhouselist;
//                    final int finalI1 = i;
//                    view.setOnClickListener(new View.OnClickListener() {
//                        @Override
//                        public void onClick(View v) {
//                            Intent itent = new Intent(HouseDetailsActivity.this, HouseDetailsActivity.class);
//                            itent.putExtra("id", ids.get(finalI) + "");
//                            itent.putExtra("city", finalGroomhouselist1.get(finalI1).getHCity() + "");
//                            HouseDetailsActivity.this.startActivity(itent);
//
//                        }
//                    });

//                }

            }
        });


        super.initView();
    }

    private void getShare(HouseDetailsBean.DataBean.HouseBean houseBean1) {


        View view33 = LayoutInflater.from(HouseDetailsActivity.this).inflate(R.layout.activity_house_details_share, null);
        scrollView1 = (MonitorScrollView) view33.findViewById(R.id.scrollview_share);
        TextView price_share = (TextView) view33.findViewById(R.id.price);
        img_share = (ImageView) view33.findViewById(R.id.img);
        TextView title_share = (TextView) view33.findViewById(R.id.house_detail_title);
        MyListView intro_share = (MyListView) view33.findViewById(R.id.house_detail_intro);
        //设置价格
        if (houseBean1 != null) {
            price_share.setText("¥" + houseBean1.getHPrice() + "/每晚");
//            ChatDao chatDao = new ChatDao(this);
//            chatDao.headBitmap_share(houseBean.getHImg1());
//            Glide.with(HouseDetailsActivity.this).load(Environment.getExternalStorageDirectory().getAbsolutePath() + "/com.weiyi.mashangzhu/share/"+ "share.jpg").into(img_share);
            title_share.setText(houseBean1.getHTitle());
            initHouseIntro_share(houseBean1, intro_share);
            Log.e("tttttttttttttttt", "=" + API.BaseApi_url + houseBean1.getHImg1());

//            Glide.with(HouseDetailsActivity.this).load(API.BaseApi_url + houseBean1.getHImg1()).listener(new RequestListener<String, GlideDrawable>() {
//                @Override
//                public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
////                    Toast.makeText(getApplicationContext(), "资源加载异常", Toast.LENGTH_SHORT).show();
//                    Log.e("tttttttttttttttt", "=资源加载异常" + API.BaseApi_url + houseBean.getHImg1());
//                    return false;
//                }
//
//                //这个用于监听图片是否加载完成
//                @Override
//                public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
////                    Toast.makeText(getApplicationContext(), "图片加载完成", Toast.LENGTH_SHORT).show();
//                    Log.e("tttttttttttttttt", "=图片加载完成" + API.BaseApi_url + houseBean.getHImg1());

//
//                    return false;
//                }
//            }).into(img);
        }


    }

    //初始化轮播图
    private void setViewPager() {
        for (int i = 0; i < urllist2.size(); i++) {
            ImageView imageview = new ImageView(this);
            imageview.setScaleType(ImageView.ScaleType.CENTER_CROP);
            Glide.with(this).load(API.BaseApi_url + urllist2.get(i)).error(R.mipmap.errer).into(imageview);
            //获取数据源
            imageViewList.add(imageview);
        }
        vp.setAdapter(new MyVpAdapter());
        vp.setCurrentItem(1000 - 1000 % imageViewList.size());
        nums.setText("1/" + urllist.size());
        handler.sendEmptyMessageDelayed(0, 2000);
        vp.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                nums.setText(position % urllist.size() + 1 + "/" + urllist.size());

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    //初始化房屋信息
    private void initHouseIntro(HouseDetailsBean.DataBean.HouseBean houseBean, ListView view) {
        String type = null;
        String typeinfo = null;
        String s2 = null;
        String s = null;
        if (houseBean.getIsWhole() == 1) {
            type = "整套出租";
            s = "房屋面积";
            s2 = "独享整套房源";
        } else if (houseBean.getIsWhole() == 0) {
            type = "独立单间";
            s = "房内";
            s2 = "与房东、可能与其他房客分住不同的房间";
        }
        if (houseBean.getHRoom() != 0 && (houseBean.getHRoom() + "") != null) {
            typeinfo = houseBean.getHRoom() + "室";
        }
        if (houseBean.getHHall() != 0 && (houseBean.getHHall() + "") != null) {
            typeinfo += houseBean.getHHall() + "厅";
        }
        if (houseBean.getHToilet() != 0 && (houseBean.getHToilet() + "") != null) {
            typeinfo += houseBean.getHToilet() + "卫";
        }
        if (houseBean.getHRooms() != 0 && (houseBean.getHRooms() + "") != null) {
            typeinfo += houseBean.getHRooms() + "厨";
        }


        List<IntroInfo> introList = new ArrayList<>();
        String htype = "";
        if ((houseBean.getHType() + "").equals("1")) {
            htype = "民居";
        } else if ((houseBean.getHType() + "").equals("2")) {
            htype = "公寓";
        } else if ((houseBean.getHType() + "").equals("3")) {
            htype = "独栋别墅";
        } else if ((houseBean.getHType() + "").equals("4")) {
            htype = "四合院";
        } else if ((houseBean.getHType() + "").equals("5")) {
            htype = "客栈";
        } else if ((houseBean.getHType() + "").equals("6")) {
            htype = "阁楼";
        }
        introList.add(new IntroInfo(R.mipmap.bed1, "房源类型", htype));
        introList.add(new IntroInfo(R.mipmap.house, type, s + houseBean.getHArea() + "平    " + typeinfo));
        introList.add(new IntroInfo(R.mipmap.mans, "宜住" + houseBean.getHPeoples() + "人", s2));
        introList.add(new IntroInfo(R.mipmap.bed, "共" + houseBean.getHBednum() + "张", houseBean.getHBedtype() + (houseBean.getHBedwidth() + "m x " + houseBean.getHBedlength() + "m")));
        IntroAdapter introAdapter = new IntroAdapter(this, introList);
        view.setAdapter(introAdapter);
        UiUtil.setListViewHeightBasedOnChildren(view);
    }
    //初始化房屋信息
    private void initHouseIntro_share(HouseDetailsBean.DataBean.HouseBean houseBean, ListView view) {
        String type = null;
        String typeinfo = null;
        String s2 = null;
        String s = null;
        if (houseBean.getIsWhole() == 1) {
            type = "整套出租";
            s = "房屋面积";
            s2 = "独享整套房源";
        } else if (houseBean.getIsWhole() == 0) {
            type = "独立单间";
            s = "房内";
            s2 = "与房东、可能与其他房客分住不同的房间";
        }
        if (houseBean.getHRoom() != 0 && (houseBean.getHRoom() + "") != null) {
            typeinfo = houseBean.getHRoom() + "室";
        }
        if (houseBean.getHHall() != 0 && (houseBean.getHHall() + "") != null) {
            typeinfo += houseBean.getHHall() + "厅";
        }
        if (houseBean.getHToilet() != 0 && (houseBean.getHToilet() + "") != null) {
            typeinfo += houseBean.getHToilet() + "卫";
        }
        if (houseBean.getHRooms() != 0 && (houseBean.getHRooms() + "") != null) {
            typeinfo += houseBean.getHRooms() + "厨";
        }


        List<IntroInfo> introList = new ArrayList<>();
        String htype = "";
        if ((houseBean.getHType() + "").equals("1")) {
            htype = "民居";
        } else if ((houseBean.getHType() + "").equals("2")) {
            htype = "公寓";
        } else if ((houseBean.getHType() + "").equals("3")) {
            htype = "独栋别墅";
        } else if ((houseBean.getHType() + "").equals("4")) {
            htype = "四合院";
        } else if ((houseBean.getHType() + "").equals("5")) {
            htype = "客栈";
        } else if ((houseBean.getHType() + "").equals("6")) {
            htype = "阁楼";
        }
//        introList.add(new IntroInfo(R.mipmap.bed1, "房源类型", htype));
        introList.add(new IntroInfo(R.mipmap.house, type, s + houseBean.getHArea() + "平    " + typeinfo));
        introList.add(new IntroInfo(R.mipmap.mans, "宜住" + houseBean.getHPeoples() + "人", s2));
        introList.add(new IntroInfo(R.mipmap.bed, "共" + houseBean.getHBednum() + "张", houseBean.getHBedtype() + (houseBean.getHBedwidth() + "m x " + houseBean.getHBedlength() + "m")));
        IntroAdapter introAdapter = new IntroAdapter(this, introList);
        view.setAdapter(introAdapter);
        UiUtil.setListViewHeightBasedOnChildren(view);
    }

    //初始化房屋设施
    private void initHouseFacility() {
        houseDetailFacility.setSelector(new ColorDrawable(Color.TRANSPARENT));
        FacilityAdapter facilityAdapter = new FacilityAdapter(this, list_yes);
        houseDetailFacility.setAdapter(facilityAdapter);
    }

    public void onEventMainThread(UpdataCalendar event) {
        adapter.notifyDataSetChanged();
        startTime.setText(startDay.getMonth() + "月" + startDay.getDay() + "日" + "\n");
        if (stopDay.getDay() == -1) {
            stopTime.setText("结束" + "\n" + "时间");
        } else {
            stopTime.setText(stopDay.getMonth() + "月" + stopDay.getDay() + "日" + "\n");
        }
    }

    //弹出框（房屋设施、退款规则）
    public void showPopupWindow(Integer s) {

        View contentView = LayoutInflater.from(this).inflate(s, null);
        final PopupWindow popupWindow = new PopupWindow(contentView,
                LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT, true);
        close = (ImageView) contentView.findViewById(R.id.close);
        if (s == R.layout.pop_win_facility) {
            MyListView listView_yes = (MyListView) contentView.findViewById(R.id.lv_yes);
            MyListView listView_no = (MyListView) contentView.findViewById(R.id.lv_no);

            listView_yes.setAdapter(new Facility_PopAdapter(this, list_yes, "yes"));
            listView_no.setAdapter(new Facility_PopAdapter(this, list_no, "no"));


        } else {
            LinearLayout l = (LinearLayout) contentView.findViewById(R.id.layout);
            for (int i = 0; i < rulesList.length; i++) {
                if (rulesList[i] != null && !rulesList[i].equals("") && rulesList[i].length() != 0) {
                    View view = LayoutInflater.from(HouseDetailsActivity.this).inflate(R.layout.item_return, null);
                    TextView t = (TextView) view.findViewById(R.id.rule);
                    t.setText(rulesList[i] + "。");
                    l.addView(view);
                }

            }
        }
        close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
        popupWindow.setTouchable(true);
        popupWindow.setAnimationStyle(R.style.popup_window_bottom_animation);
        popupWindow.setBackgroundDrawable(new ColorDrawable(0x55000000));
        popupWindow.showAtLocation(contentView, Gravity.CENTER, 0, 0);
    }

    private Bitmap loadBitmapFromView(View v) {
        int w = v.getWidth();
        int h = v.getHeight();
        Bitmap bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(bmp);

        c.drawColor(Color.WHITE);
        /** 如果不设置canvas画布为白色，则生成透明 */

        v.layout(0, 0, w, h);
        v.draw(c);

        return bmp;
    }

    /**
     * 把一个view转化成bitmap对象
     */
    public Bitmap getViewBitmap(int layoutId) {
        View view = getLayoutInflater().inflate(layoutId, null);
        int me = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        view.measure(me, me);
        view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
        view.buildDrawingCache();
        Bitmap bitmap = view.getDrawingCache();

        return bitmap;
    }

    //然后View和其内部的子View都具有了实际大小，也就是完成了布局，相当与添加到了界面上。接着就可以创建位图并在上面绘制了：
    private void layoutView(View v, int width, int height) {
        // 指定整个View的大小 参数是左上角 和右下角的坐标
        v.layout(0, 0, width, height);
        int measuredWidth = View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY);
        int measuredHeight = View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.AT_MOST);
        /** 当然，measure完后，并不会实际改变View的尺寸，需要调用View.layout方法去进行布局。
         * 按示例调用layout函数后，View的大小将会变成你想要设置成的大小。
         */
        v.measure(measuredWidth, measuredHeight);
        v.layout(0, 0, v.getMeasuredWidth(), v.getMeasuredHeight());
    }

    //弹出框（分享）
    public void showPopupWindow() {

        View contentView = LayoutInflater.from(this).inflate(R.layout.pop_win_friend, null);
        final PopupWindow popupWindow = new PopupWindow(contentView,
                LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT, true);
        pop_friend_wx = (TextView) contentView.findViewById(R.id.pop_friend_wx);
        pop_friend_wxc = (TextView) contentView.findViewById(R.id.pop_friend_wxc);
        pop_off = (TextView) contentView.findViewById(R.id.pop_off);
        pop_off.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
        pop_friend_wx.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                T.showShort(HouseDetailsActivity.this, "分享给微信好友");
                msgApi = WXAPIFactory.createWXAPI(HouseDetailsActivity.this, null);
                msgApi.registerApp("wx29a520b1867fe3a2");
                if (!MyApp.mWxApi.isWXAppInstalled()) {
                    T.showShort(HouseDetailsActivity.this, "您还未安装微信客户端");
                    return;
                }
                DisplayMetrics metric = new DisplayMetrics();
                getWindowManager().getDefaultDisplay().getMetrics(metric);
                final int width = metric.widthPixels;     // 屏幕宽度（像素）
                final int height = metric.heightPixels;   // 屏幕高度（像素）
                layoutView(scrollView1, width, height);
                bitmap = loadBitmapFromView(scrollView1);
                if (bitmap != null) {
                    sharePicByFile(bitmap, System.currentTimeMillis() + "", "好友");
                    popupWindow.dismiss();
                } else {
                    T.showShort(HouseDetailsActivity.this, "分享页面加载失败，请稍后再试");
                }
//           getShare();
//                popupWindow.dismiss();


            }
        });
        pop_friend_wxc.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                T.showShort(HouseDetailsActivity.this, "分享到朋友圈");
                popupWindow.dismiss();
                msgApi = WXAPIFactory.createWXAPI(HouseDetailsActivity.this, null);
                msgApi.registerApp("wx29a520b1867fe3a2");
                if (!MyApp.mWxApi.isWXAppInstalled()) {
                    T.showShort(HouseDetailsActivity.this, "您还未安装微信客户端");
                    return;
                }
//                layoutView(scrollView1, width, height);
//                Bitmap bitmap = loadBitmapFromView(scrollView1);
                DisplayMetrics metric = new DisplayMetrics();
                getWindowManager().getDefaultDisplay().getMetrics(metric);
                final int width = metric.widthPixels;     // 屏幕宽度（像素）
                final int height = metric.heightPixels;   // 屏幕高度（像素）
                layoutView(scrollView1, width, height);
                bitmap = loadBitmapFromView(scrollView1);
                if (bitmap != null) {
                    sharePicByFile(bitmap, System.currentTimeMillis() + "", "朋友圈");
                    popupWindow.dismiss();
                } else {
                    T.showShort(HouseDetailsActivity.this, "分享页面加载失败，请稍后再试");
                }
//                Bitmap bitmap = getBitmapByView(scrollview);
//                if (bitmap != null) {
//                    sharePicByFile(bitmap, System.currentTimeMillis() + "", "朋友圈");
//                } else {
//                    T.showShort(HouseDetailsActivity.this, "图片为空");
//                }
            }
        });
        popupWindow.setTouchable(true);
        popupWindow.setAnimationStyle(R.style.popup_window_bottom_animation);
        popupWindow.setBackgroundDrawable(new ColorDrawable(0x55000000));
        // 设置好参数之后再show
        if (popupWindow.isShowing()) {

        } else {
            popupWindow.showAsDropDown(contentView);
        }

    }

    public static Bitmap getBitmapByView(ScrollView scrollView) {
        int h = 0;
        Bitmap bitmap = null;
        for (int i = 0; i < scrollView.getChildCount(); i++) {
            h += scrollView.getChildAt(i).getHeight();
        }
        bitmap = Bitmap.createBitmap(scrollView.getWidth(), h,
                Bitmap.Config.RGB_565);
        final Canvas canvas = new Canvas(bitmap);
        scrollView.draw(canvas);
        return bitmap;
    }

    public void sharePicByFile(Bitmap bitmap, String tag, String info) {
//        if (!picFile.exists()) {return;}
//        Bitmap pic = BitmapFactory.decodeFile(picFile.toString());

        WXImageObject imageObject = new WXImageObject(bitmap);
        //这个构造方法中自动把传入的bitmap转化为2进制数据,或者你直接传入byte[]也行
        //注意传入的数据不能大于10M,开发文档上写的

        WXMediaMessage msg = new WXMediaMessage();  //这个对象是用来包裹发送信息的对象
        msg.mediaObject = imageObject;
        //msg.mediaObject实际上是个IMediaObject对象,
        //它有很多实现类,每一种实现类对应一种发送的信息,
        //比如WXTextObject对应发送的信息是文字,想要发送文字直接传入WXTextObject对象就行


        Bitmap thumbBitmap = Bitmap.createScaledBitmap(bitmap, 150, 150, true);

        msg.thumbData = BmpToByteArray.bmpToByteArray(thumbBitmap);
        //在这设置缩略图
        //官方文档介绍这个bitmap不能超过32kb
        //如果一个像素是8bit的话换算成正方形的bitmap则边长不超过181像素,边长设置成150是比较保险的
        //或者使用msg.setThumbImage(thumbBitmap);省去自己转换二进制数据的过程
        //如果超过32kb则抛异常

        SendMessageToWX.Req req = new SendMessageToWX.Req();    //创建一个请求对象
        req.message = msg;  //把msg放入请求对象中
        if (info.equals("朋友圈")) {
            req.scene = SendMessageToWX.Req.WXSceneTimeline;    //设置发送到朋友圈
        } else {
            req.scene = SendMessageToWX.Req.WXSceneSession;   //设置发送给朋友
        }
        req.transaction = tag;  //这个tag要唯一,用于在回调中分辨是哪个分享请求
        boolean b = msgApi.sendReq(req);   //如果调用成功微信,会返回true
        Log.e("==============", "==" + b);
    }

    //弹出框（日期选择）
    public void showPopupWindow_date() {
        View contentView = LayoutInflater.from(this).inflate(R.layout.pop_win_date, null);
        final PopupWindow popupWindow = new PopupWindow(contentView,
                LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT, true);

        startTime = (TextView) contentView.findViewById(R.id.plan_time_txt_start);
        stopTime = (TextView) contentView.findViewById(R.id.plan_time_txt_stop);
        ImageView close = (ImageView) contentView.findViewById(R.id.close);
        close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
        reycycler = (RecyclerView) contentView.findViewById(R.id.plan_time_calender);
        LinearLayoutManager layoutManager =
                new LinearLayoutManager(this,   // 上下文
                        LinearLayout.VERTICAL,  //垂直布局,
                        false);

        reycycler.setLayoutManager(layoutManager);

        MoveToPosition(layoutManager, reycycler, isPreferences.getSp().getInt("start_month_position", 0));


        popupWindow.setTouchable(true);
        popupWindow.setAnimationStyle(R.style.popup_window_bottom_animation);
        popupWindow.setBackgroundDrawable(new ColorDrawable(0x55000000));
        // 设置好参数之后再show
        popupWindow.showAtLocation(contentView, Gravity.CENTER, 0, 0);
        initData(popupWindow);

    }

    private void initData(final PopupWindow popupWindow) {
        startDay = new DayTimeEntity(0, 0, 0, 0);
        stopDay = new DayTimeEntity(-1, -1, -1, -1);
        datas = new ArrayList<>();

        Calendar c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH) + 1;

        datas.add(new MonthTimeEntity(year, month));                //

        for (int i = 0; i < 6; i++) {
            MonthTimeEntity monthTimeEntity = new MonthTimeEntity();
            if (month >= 12) {//明年
                year = c.get(Calendar.YEAR) + 1;
                month = 1;
                monthTimeEntity.setYear(year);
                monthTimeEntity.setMonth(month);
            } else {
                month = month + 1;
                monthTimeEntity.setYear(year);
                monthTimeEntity.setMonth(month);
            }

            datas.add(monthTimeEntity);

        }

        adapter = new MonthTimeAdapter_HouseDetails(datas, this);
        reycycler.setAdapter(adapter);
        adapter.setOnDayItemClickListener(new MonthTimeAdapter_HouseDetails.OnDayItemClickListener() {
            @Override
            public void OnDayItemClick(View view, int position) {
                isPreferences.updateSp("start_month_position", startDay.getMonthPosition());
                isPreferences.updateSp("start_day_position", startDay.getDayPosition());
                isPreferences.updateSp("end_month_position", stopDay.getMonthPosition());
                isPreferences.updateSp("end_day_position", stopDay.getDayPosition());

                isPreferences.updateSp("start_year", startDay.getYear());
                isPreferences.updateSp("start_month", startDay.getMonth());
                isPreferences.updateSp("start_day", startDay.getDay());

                isPreferences.updateSp("end_year", stopDay.getYear());
                isPreferences.updateSp("end_month", stopDay.getMonth());
                isPreferences.updateSp("end_day", stopDay.getDay());


                Intent i = new Intent();
                i.putExtra("start_year", startDay.getYear());
                i.putExtra("start_month", startDay.getMonth());
                i.putExtra("start_day", startDay.getDay());

                i.putExtra("end_year", stopDay.getYear());
                i.putExtra("end_month", stopDay.getMonth());
                i.putExtra("end_day", stopDay.getDay());
                setResult(RESULT_OK, i);
                popupWindow.dismiss();
                start_time = startDay.getYear() + "-" + startDay.getMonth() + "-" + startDay.getDay();
                stop_time = stopDay.getYear() + "-" + stopDay.getMonth() + "-" + stopDay.getDay();
                time.setText(startDay.getYear() + "." + startDay.getMonth() + "." + startDay.getDay() + "-" + stopDay.getYear() + "." + stopDay.getMonth() + "." + stopDay.getDay());
            }
        });

    }

    //直接显示第n个item内容
    public static void MoveToPosition(LinearLayoutManager manager, RecyclerView mRecyclerView, int n) {
        int firstItem = manager.findFirstVisibleItemPosition();
        int lastItem = manager.findLastVisibleItemPosition();
        if (n <= firstItem) {
            mRecyclerView.scrollToPosition(n);
        } else if (n <= lastItem) {
            int top = mRecyclerView.getChildAt(n - firstItem).getTop();
            mRecyclerView.scrollBy(0, top);
        } else {
            mRecyclerView.scrollToPosition(n);
        }

    }

    private void scrollChangeBarBg() {
        scrollview.setOnScrollListener(new OnScrollListener() {

            @Override
            public void onScroll() {
                int[] ints = new int[2];
                vp.getLocationOnScreen(ints);
                int scrollY = -ints[1];
                int imageHeight = vp.getHeight();
                if (vp != null && imageHeight > 0) {
                    if (scrollY <= 0) {
                        title.getBackground().setAlpha(0);
                        tvTop.setVisibility(View.GONE);
                    } else {
                        if (scrollY < imageHeight) {
                            float progress = new Float(scrollY) / new Float(imageHeight) * 255;
                            tvTop.setVisibility(View.VISIBLE);
                            title.getBackground().setAlpha((int) progress);
                        } else {
                            title.getBackground().setAlpha(255);
                            tvTop.setVisibility(View.VISIBLE);
                        }
                    }
                }
            }
        });
    }

    //需要做是否以登录判断的操作
    public void isLogin(String type) {
        if (SPUtils.get(this, "isLogin", "0").equals("0")) {
            UiUtil.startActivity(this, LoginActivity.class);
        } else if (SPUtils.get(this, "isLogin", "0").equals("1")) {
            //已登录
            //已登录 进行收藏操作
            if (type.equals("collect")) {
                if (houseDetailsBean.getData().getHouse().getIsCollect().equals("0")) {

                    OkHttpUtils.get().addParams("token", SPUtils.get(this, "token", "") + "")
                            .addParams("id", houseDetailsBean.getData().getHouse().getId() + "")
//                            .addParams("favstatus", "0")
                            .url(API.BaseApi_R + API.CollectHouse_Api)
                            .build()
                            .execute(new StringCallback() {
                                @Override
                                public void onError(Request request, Exception e) {
                                    T.showShort(HouseDetailsActivity.this, "收藏失败");
                                }

                                @Override
                                public void onResponse(String response) {
                                    Log.e("tyyyyyyyy", "re=" + response);
                                    try {
                                        JSONObject jsonObject = new JSONObject(response);
                                        if (jsonObject.getInt("status") == 0) {

                                            collect.setImageResource(R.mipmap.collect1);
                                            houseDetailsBean.getData().getHouse().setIsCollect("1");
                                            T.showShort(HouseDetailsActivity.this, "收藏成功");
                                        }
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            });
                } else if (houseDetailsBean.getData().getHouse().getIsCollect().equals("1")) {

                    OkHttpUtils.get().addParams("token", SPUtils.get(this, "token", "") + "")
                            .addParams("id", houseDetailsBean.getData().getHouse().getId() + "")
//                            .addParams("favstatus", "1")
                            .url(API.BaseApi_R + API.CollectHouse_Api)
                            .build()
                            .execute(new StringCallback() {
                                @Override
                                public void onError(Request request, Exception e) {
                                    T.showShort(HouseDetailsActivity.this, "取消收藏失败");
                                }

                                @Override
                                public void onResponse(String response) {
                                    Log.e("tyyyyyyyy", "re=" + response);
                                    try {
                                        JSONObject jsonObject = new JSONObject(response);
                                        if (jsonObject.getInt("status") == 0) {
                                            collect.setImageResource(R.mipmap.collect);
                                            houseDetailsBean.getData().getHouse().setIsCollect("0");
                                            T.showShort(HouseDetailsActivity.this, "取消收藏成功");
                                        }
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            });
                }

            } else if (type.equals("share")) {
                showPopupWindow();
            } else if (type.equals("chat")) {
                UiUtil.startActivity(this, MessageDetailsActivity.class);
            } else if (type.equals("order")) {
                final String s = time.getText() + "";
                final String[] strings = s.split("-");
                if (s.equals("") || s == null) {
                    T.showShort(this, "请选择入住日期");
                } else {
                    LoadingDialog.show(HouseDetailsActivity.this);
                    OkHttpUtils.get().addParams("token", SPUtils.get(this, "token", "") + "")
                            .url(API.BaseApi_R + API.CheckIdCard_Api)
                            .build()
                            .execute(new StringCallback() {
                                @Override
                                public void onError(Request request, Exception e) {
                                    LoadingDialog.dismiss(HouseDetailsActivity.this);
                                    T.showShort(HouseDetailsActivity.this, "数据获取失败，请稍后再试");
                                }

                                @Override
                                public void onResponse(String response) {
                                    try {

                                        JSONObject jsonObject = new JSONObject(response);
                                        if (jsonObject.getInt("status") == 0) {
                                            if (jsonObject.getJSONObject("data").getInt("uCheckid") == 1) {
                                                //已经进行过身份认证 预定房间
                                                Log.e("vbbbbbb", "==" + SPUtils.get(HouseDetailsActivity.this, "token", "") + "");
                                                Log.e("vbbbbbb", "==" + house_id);
                                                Log.e("vbbbbbb", "==" + strings[0].replace(".", "-"));
                                                Log.e("vbbbbbb", "==" + strings[1].replace(".", "-"));
                                                Log.e("vbbbbbb", "==" + yajin);
                                                OkHttpUtils.get().addParams("token", SPUtils.get(HouseDetailsActivity.this, "token", "") + "")
                                                        .addParams("houseId", house_id)
                                                        .addParams("oLivetime", strings[0].replace(".", "-"))
                                                        .addParams("oCheckouttime", strings[1].replace(".", "-"))
                                                        .addParams("oDeposit", yajin)
                                                        .url(API.BaseApi_R + API.GoOrder_Api)
                                                        .build()
                                                        .execute(new StringCallback() {
                                                            @Override
                                                            public void onError(Request request, Exception e) {
                                                                LoadingDialog.dismiss(HouseDetailsActivity.this);
                                                                T.showShort(HouseDetailsActivity.this, "数据获取失败，请稍后再试");
                                                            }

                                                            @Override
                                                            public void onResponse(String response) {
                                                                LoadingDialog.dismiss(HouseDetailsActivity.this);
                                                                try {

                                                                    JSONObject jsonObject = new JSONObject(response);
                                                                    if (jsonObject.getInt("status") == 0) {
                                                                        Intent intent1 = new Intent(HouseDetailsActivity.this, MainActivity_R.class);
                                                                        intent1.putExtra("info", 1);
                                                                        startActivity(intent1);
                                                                    }
                                                                    T.showShort(HouseDetailsActivity.this, jsonObject.getString("msg"));

                                                                } catch (JSONException e) {
                                                                    e.printStackTrace();
                                                                }
                                                            }
                                                        });
                                            } else {
                                                //进行身份认证
                                                LoadingDialog.dismiss(HouseDetailsActivity.this);
                                                UiUtil.startActivity(HouseDetailsActivity.this, IdentityActivity.class);
                                            }
                                        }
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            });


//                    Intent intent1 = new Intent(this, OrderDetailActivity.class);
//                    intent1.putExtra("info", "r");
//                    intent1.putExtra("house_id", house_id);
//                    intent1.putExtra("start_time", strings[0].replace(".", "-"));
//                    intent1.putExtra("stop_time", strings[1].replace(".", "-"));
//                    intent1.putExtra("yajin", yajin);
//                    startActivity(intent1);
                }
            }
        }
    }

    @OnClick({R.id.house_detail_reserve, R.id.house_detail_chat, R.id.house_detail_calendar, R.id.house_detail_description_full, R.id.house_detail_good, R.id.back, R.id.collect, R.id.share, R.id.house_detail_owner, R.id.house_detail_notice_policy, R.id.house_detail_facility_more})
    public void onViewClicked(View view) {
        Intent intent = null;
        switch (view.getId()) {

            case R.id.back:
                finish();
                break;
            case R.id.collect:
                isLogin("collect");
                break;
            case R.id.share:
                isLogin("share");

                break;
            case R.id.house_detail_owner:
                intent = new Intent(this, LandlordInfoActivity.class);
                intent.putExtra("id", houseDetailsBean.getData().getSellerId() + "");
                intent.putExtra("city", houseDetailsBean.getData().getHouse().getHCity() + "");
                startActivity(intent);
                break;
            case R.id.house_detail_notice_policy:
                showPopupWindow(R.layout.pop_win_refund_rule);
                break;
            case R.id.house_detail_facility_more:
                showPopupWindow(R.layout.pop_win_facility);
                break;
            case R.id.house_detail_good:
                intent = new Intent(this, AllCommentActivity.class);
                intent.putExtra("type", "house");
                intent.putExtra("id", houseDetailsBean.getData().getHouse().getId() + "");
                startActivity(intent);
                break;
            case R.id.house_detail_description_full:
                initHouseDescription();
                break;
            case R.id.house_detail_calendar:
                showPopupWindow_date();
                break;
            case R.id.house_detail_chat:
                chat();
                break;
            case R.id.house_detail_reserve:
                isLogin("order");
                break;


        }
    }

    private void chat() {

        LoadingDialog.show(this);

        if (SPUtils.get(HouseDetailsActivity.this, "isLogin", "0").equals("0")) {
            UiUtil.startActivity(HouseDetailsActivity.this, LoginActivity.class);
        } else if (SPUtils.get(HouseDetailsActivity.this, "isLogin", "0").equals("1")) {
            if (houseDetailsBean != null) {
                HouseDetailsBean.DataBean data = houseDetailsBean.getData();
                if (data != null) {
                    String sellerId = data.getSellerId();
                    if (sellerId != null) {
                        initNickAndHead(sellerId);
                    }
                }
            }
        }
    }

    private void initNickAndHead(final String id) {
        OkHttpUtils.get().addParams("id", id).url(API.BaseApi_R + API.findHeadandName).build().execute(new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {

            }

            @Override
            public void onResponse(String response) {
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    if (jsonObject.getInt("status") == 0) {
                        JSONObject jsonObject1 = jsonObject.getJSONObject("data");
                        String uNickname = jsonObject1.getString("uNickname");
                        String uHead = jsonObject1.getString("uHead");
                        saveNickAndAvatar(id, uNickname, uHead);
                    }
                } catch (JSONException e) {

                }
            }
        });
    }

    private void saveNickAndAvatar(String userAccount, String uNickname, String uHead) {
        ChatDao chatDao = new ChatDao(this);
        if (!chatDao.isExist(userAccount)) {
            chatDao.add(userAccount, uNickname, uHead);
        } else {
            chatDao.update(userAccount, uNickname, uHead);
        }

        startChat(userAccount, uNickname, uHead);
    }

    private void startChat(String sellerId, String uNickname, String uHead) {
        ChatDao chatDao = new ChatDao(this);
        String tagHead = chatDao.convertFileName(uHead);
//        String[] leftAccount = chatDao.findByAccount(sellerId);

        String rightHead = "";
        String token = SPUtils.get(this, "token", "") + "";
        String[] split = token.split("@");
        if (split.length > 1) {
            String userAccount = split[1];
            if (userAccount != null) {
                String[] rightAccount = chatDao.findByAccount(userAccount);
                if (rightAccount != null && rightAccount.length > 0) {
                    rightHead = rightAccount[1];
                }
            }
        }

        Intent chat = new Intent(HouseDetailsActivity.this, ChatActivity.class);
        chat.putExtra("userId", sellerId);
        chat.putExtra(Constant.LEFT_NICK, uNickname);
        chat.putExtra(Constant.LEFT_HEAD, tagHead);
//        if (leftAccount != null && leftAccount.length > 0) {
//            chat.putExtra(Constant.LEFT_NICK, leftAccount[0]);
//            chat.putExtra(Constant.LEFT_HEAD, leftAccount[1]);
//        }
        chat.putExtra("firstChat", "1");
        chat.putExtra(Constant.RIGHT_HEAD, rightHead);
        startActivity(chat);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        mMapView.onDestroy();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mMapView.onPause();
    }

    class MyVpAdapter extends PagerAdapter {

        @Override
        public int getCount() {
            return Integer.MAX_VALUE;
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            ViewGroup parent = (ViewGroup) imageViewList.get(position % imageViewList.size()).getParent();

            if (parent != null) {

                parent.removeAllViews();

            }
            ((ViewPager) container).addView(imageViewList.get(position % imageViewList.size()), 0);
            return imageViewList.get(position % imageViewList.size());
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            ((ViewPager) container).removeView(imageViewList.get(position % imageViewList.size()));
        }
    }
}
